﻿using Common;
using Orleans;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Server.Impl
{
    /// <summary>
    /// 交管区锁AGV，一个区域一个GRAIN
    /// </summary>
    internal class AreaLockImpl : Grain, IAreaLock
    {
        private readonly IPersistentState<LockItem> cache;

        public AreaLockImpl([PersistentState("areaLock", "redisStorage")] IPersistentState<LockItem> persistent)
        {
            this.cache = persistent;
        }

        public override async Task OnActivateAsync()
        { 
            await cache.ReadStateAsync(); 
            await base.OnActivateAsync();
        }


        

        public async Task<bool> AGV进入区域(long AgvID)
        {
            if(cache.State.IsLocked == false)
            {
                //没上锁到上锁
                cache.State.IsLocked = true;
                cache.State.AgvID = AgvID;
                await cache.WriteStateAsync();
                return false;
            }
            //以下是上锁的
            if (cache.State.AgvID == AgvID)
            {
                //上锁是自己，不处理
                return false;
            }
            else
            {
                //需要停下来 
                if (cache.State.StopList.Contains(AgvID) == false)
                {
                    cache.State.StopList.Add(AgvID);
                    await cache.WriteStateAsync();
                }
                return true;
            }

        }

      

        public async Task<long>  释放区域()
        {
            if (cache.State.IsLocked == false)
            {
                //根本没上锁
                return 0;
            }
            if(cache.State.StopList.Count > 0)
            {
                //有AGV停下来
                long AgvID = cache.State.StopList[0];
                cache.State.AgvID=AgvID;
                cache.State.StopList.RemoveAt(0);
                await cache.WriteStateAsync(); 
                return AgvID;
            }
            else  
            {
                //空区域
                cache.State.AgvID = 0;
                cache.State.IsLocked=false;
                await cache.WriteStateAsync(); 
                return 0;
            } 
        }
    }

    #region 数据定义

    internal class LockItem
    { 
        /// <summary>
        /// 上锁标识
        /// </summary>
        public bool IsLocked { get; set; }

        /// <summary>
        /// 上锁的AGV
        /// </summary>
        public long AgvID { get; set; }

        /// <summary>
        /// 被交管的AGV列表
        /// </summary>
        public List<long> StopList { get; set; } = new List<long>();
    }

    #endregion
}
